package data;

import java.util.ArrayList;

import models.MessageQueue;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class MessageQueueData {
	private static Objectify ofy;
	
	public static void insert(MessageQueue messageQueue) {
		init();
		ofy.put(messageQueue);
	}
	
	public static MessageQueue getMessageQueueForCrawler() {
		init();
		MessageQueue messageQueue = new MessageQueue();
		messageQueue = ofy.query(MessageQueue.class).filter("isDone", false).get();
		return messageQueue;
	}
	
	public static MessageQueue getById(String id) {
		init();
		MessageQueue messageQueue  = new MessageQueue();
		try {
			messageQueue = ofy.get(new Key<MessageQueue>(MessageQueue.class, id));
		} catch (Exception e) {
			messageQueue = null;
		}
		return messageQueue;
	}
	
	public static ArrayList<MessageQueue> getAll() {
		init();
		ArrayList<MessageQueue> mqs = new ArrayList<MessageQueue>();
		Query<MessageQueue> q = ofy.query(MessageQueue.class).limit(20);
		
		for (MessageQueue messageQueue: q) {
			mqs.add(messageQueue);
		}
		
		return mqs;
	}
	
	public static void deleteAll() {
		init();
		Query<MessageQueue> q = ofy.query(MessageQueue.class).limit(500);
		for (MessageQueue messageQueue: q) {
			ofy.delete(messageQueue);
		}
	}
	
	private static void init() {
		try {
			ObjectifyService.register(MessageQueue.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		ofy = ObjectifyService.begin();
	}
}
